// pages/profile/index.js
const app = getApp();
const api = app.api;
const wxutil = app.wxutil;
const pageSize = 16; // 每页显示条数

Page({
  data: {
    user: {},
    showPopup: false,
    topics: [],
    comments: [],
    pageTopic: 1,
    pageComment: 1,
    tabIndex: 0,
    tabsTop: 255,
    isAuth: false,
    tabsFixed: false, // Tabs是否吸顶
    isEndTopic: false, // 话题是否到底
    isEndComment: false, // 评论是否到底
    loading: false,
  },

  onLoad() {
    this.getTabsTop();
  },

  onShow() {
    this.getUser();

    const userId = this.data.user.id;

    if (!userId) {
      // 数据初始化
      this.setData({
        topics: [],
        comments: [],
        pageTopic: 1,
        pageComment: 1,
        isEndTopic: false,
        isEndComment: false,
      });
    }
  },

  /**
   * 获取Tabs的高度
   */
  getTabsTop() {
    const navigateHeight = 56;
    const query = wx.createSelectorQuery();
    query.select("#tabs").boundingClientRect((res) => {
      this.setData({
        tabsTop: res.top - navigateHeight,
      });
    }).exec();
  },

  /**
   * 获取用户信息
   */
  getUser() {
    let userDetail = app.globalData.userDetail;
    // 授权用户使用userDetail作为用户信息
    if (userDetail) {
      const userId = userDetail.id;
      const url = api.userAPI + userId + "/";

      wxutil.request.get(url).then((res) => {
        if (res.data.code == 200) {
          // 更新缓存
          const user = res.data.data;
          userDetail = Object.assign(userDetail, user);
          wxutil.setStorage("userDetail", userDetail);
          app.globalData.userDetail = userDetail;

          this.setData({
            isAuth: true,
            user: userDetail,
          });

          const tabIndex = this.data.tabIndex;
          if (tabIndex == 0) {
            this.getTopics();
          }
          if (!this.data.user.is_register) {
            wx.navigateTo({
              url: '../user-edit/index',
            });
          }
        }
      });
    } else {
      this.setData({
        user: {},
        isAuth: false,
      });
    }
  },

  /**
   * 获取用户话题
   */
  getTopics(pageTopic = 1, size = pageSize) {
    const url = api.userAPI + "rent";
    let data = {
      size: size,
      page: pageTopic,
    };

    if (this.data.isEndTopic && pageTopic != 1) {
      return;
    }

    wxutil.request.get(url, data).then((res) => {
      if (res.data.code == 200) {
        const topics = res.data.data;
        this.setData({
          pageTopic: (topics.length == 0 && pageTopic != 1) ? pageTopic - 1 : pageTopic,
          loading: false,
          isEndTopic: ((topics.length < pageSize) || (topics.length == 0 && pageTopic != 1)) ? true : false,
          topics: pageTopic == 1 ? topics : this.data.topics.concat(topics),
        });
      } else if (res.statusCode == 500){
        this.clearStorage()
      }
    });
  },

   /**
   * 清除缓存
   */
  clearStorage() {
    wx.lin.showDialog({
      type: "confirm",
      title: "提示",
      content: "登录过期，点击清除缓存",
      success: (res) => {
        if (res.confirm) {
          wx.clearStorage();
          app.globalData.userDetail = null;
          wx.lin.showMessage({
            type: "success",
            content: "清除成功！",
          });
          wx.navigateTo({
            url: '../auth/index',
          })
        }
      },
    });
  },

  /**
   * 获取用户评论
   */
  getComments(pageComment = 1, size = pageSize) {
    const url = api.userAPI + "post";
    let data = {
      size: size,
      page: pageComment,
    };

    if (this.data.isEndComment && pageComment != 1) {
      return;
    }

    wxutil.request.get(url, data).then((res) => {
      if (res.data.code == 200) {
        const comments = res.data.data;
        this.setData({
          pageComment: (comments.length == 0 && pageComment != 1) ? pageComment - 1 : pageComment,
          loading: false,
          isEndComment: ((comments.length < pageSize) || (comments.length == 0 && pageComment != 1)) ? true : false,
          comments: pageComment == 1 ? comments : this.data.comments.concat(comments),
        });
      }
    });
  },

  /**
   * Tab切换
   */
  changeTabs(event) {
    const tabIndex = event.detail.currentIndex;
    const userId = this.data.user.id;
    this.setData({
      tabIndex: tabIndex,
    });

    if (userId) {
      if (tabIndex == 0) {
        this.getTopics();
      }
      if (tabIndex == 1) {
        this.getComments();
      }
    }
  },

  /**
   * 跳转到授权页面
   */
  gotoAuth() {
    wx.navigateTo({
      url: "/pages/auth/index",
    });
  },

  /**
   * 跳转到编辑资料页面
   */
  gotoUserEdit() {
    wx.navigateTo({
      url: "/pages/user-edit/index",
    });
  },

  /**
   * 跳转话题详情页
   */
  gotoTopicDetail(event) {
    const orderId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/rent-detail/index?orderId=" + orderId,
    });
  },

  gotoChatRoom(event) {
    const roomId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/post-detail/index?orderId=" + roomId,
    });
  },

  PostDevice() {
    wx.navigateTo({
      url: '../post-device/index',
    });
  },

  /**
   * 修改封面
   */
  changePoster() {
    wx.lin.showMessage({
      content: "设置封面图片",
    });

    // 上传封面
    wxutil.image.choose(1).then((res) => {
      if (res.errMsg == "chooseImage:ok") {
        wxutil.showLoading("上传中...");
        const url = api.userAPI + "poster/";

        wxutil.file.upload({
          url: url,
          fileKey: "file",
          filePath: res.tempFilePaths[0],
        }).then((res) => {
          const data = JSON.parse(res.data);
          if (data.code == 200) {
            wx.hideLoading();
            // 更新缓存
            const user = data.data;
            let userDetail = app.globalData.userDetail;
            userDetail = Object.assign(userDetail, user);
            wxutil.setStorage("userDetail", userDetail);
            app.globalData.userDetail = userDetail;

            this.setData({
              user: user,
            });

            wx.lin.showMessage({
              type: "success",
              content: "封面修改成功！",
            });
          } else {
            wx.lin.showMessage({
              type: "error",
              content: "封面修改失败！",
            });
          }
        });
      }
    });
  },

  /**
   * 修改头像
   */
  changeAvatar() {
    wx.lin.showMessage({
      content: "设置头像图片",
    });
    wxutil.image.choose(1).then((res) => {
      if (res.errMsg == "chooseImage:ok") {
        wx.navigateTo({
          url: "/pages/images-cropper/index?src=" + res.tempFilePaths[0],
        });
      }
    });
  },

  /**
   * 触底加载
   */
  onReachBottom() {
    const tabIndex = this.data.tabIndex;

    this.setData({
      loading: true,
    });
    if (tabIndex == 0) {
      const page = this.data.pageTopic;
      this.getTopics(page + 1);
    }
    if (tabIndex == 1) {
      const page = this.data.pageComment;
      this.getComments(page + 1);
    }
  },

  /**
   * 删除话题
   */
  deleteTopic(event) {
    wx.lin.showDialog({
      type: "confirm",
      title: "提示",
      content: "确定要删除该订单？",
      success: (res) => {
        if (res.confirm) {
          const orderId = event.currentTarget.dataset.id;
          const url = api.userAPI + "rent/" + orderId;

          wxutil.request.delete(url).then((res) => {
            if (res.data.code == 200) {
              this.getTopics(this.data.user.id);

              wx.lin.showMessage({
                type: "success",
                content: "删除成功！",
              });
            } else {
              wx.lin.showMessage({
                type: "error",
                content: "删除失败！",
              });
            }
          });
        }
      },
    });
  },

  /**
   * 删除评论
   */
  deleteComment(event) {
    wx.lin.showDialog({
      type: "confirm",
      title: "提示",
      content: "确定要删除该订单？",
      success: (res) => {
        if (res.confirm) {
          const commentId = event.currentTarget.dataset.id;
          const url = api.userAPI + "post/" + commentId;

          wxutil.request.delete(url).then((res) => {
            if (res.data.code == 200) {

              this.getComments(this.data.user.id);

              wx.lin.showMessage({
                type: "success",
                content: "删除成功！",
              });
            } else {
              wx.lin.showMessage({
                type: "error",
                content: "删除失败！",
              });
            }
          });
        }
      },
    });
  },

  onPageScroll(event) {
    if (event.scrollTop >= this.data.tabsTop) {
      this.setData({
        tabsFixed: true,
      });
    } else {
      this.setData({
        tabsFixed: false,
      });
    }
  },
  /**
   * 图片预览
   */
  previewImage(event) {
    const src = event.currentTarget.dataset.src;
    const urls = [src];

    wx.previewImage({
      current: "",
      urls: urls,
    });
  },

  editInfo() {
    wx.navigateTo({
      url: "/pages/edit-info/index",
    });
  },

  onEditTap() {
    if (app.globalData.userDetail) {
      wx.navigateTo({
        url: "/pages/edit-info/index",
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/index",
      });
    }
  },
});

